"""
有yield关键字的函数不再是普通函数，调用函数会得到生成器对象（协程对象）
要使用协程对象，要先做一次预激，比如协程对象名字叫ca：
    ~ next(ca)
    ~ ca.send(None)
协程是实现协作式并发（异步编程）的核心机制，异步I/O是异步编程的一部分
"""
import asyncio
import random
import uvloop


# @asyncio.coroutine
# def say_hello(name):
#     print(f'Hello, {name}!')


async def say_hello(name, delay):
    await asyncio.sleep(delay)
    print(f'Hello, {name}!')


asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(
    [say_hello(name, random.randint(1, 5)) 
     for name in ('Jack', 'Tom', 'Jerry')]
))


def gen_character():
    # 嵌套生成器
    yield from 'abcdeghijklmnopqrstuvwxyz'
    yield from range(10)


def calc_average():
    total, counter, average = 0, 0, None
    while True:
        num = yield average
        total += num
        counter += 1
        average = total / counter
